//同时发送异步代码的次数;
let ajaxTimes = 0;

export const request = (params) => {
  //判断传递过来参数的url是否带有/my/ 如果有带那么添加token,如果没带就不添加;
  let header = { ...params.header };
  if (params.url.includes("/my/")) {
    //在原有header的基础之上携带一个字段Authorization 它的值是token;
    header["Authorization"] = wx.getStorageSync("token");
  }

  ajaxTimes++;
  //显示出加载中;
  wx.showLoading({
    title: "加载中",
    mask: true,
  });

  //定义公共的url
  const baseUrl = "https://api-hmugo-web.itheima.net/api/public/v1";
  // https://api-hmugo-web.itheima.net/api/public/v1"

  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      header: header,
      url: baseUrl + params.url,
      success: (result) => {
        resolve(result.data.message);
      },
      fail: (err) => {
        reject(err);
      },
      complete: () => {
        ajaxTimes--;
        if (ajaxTimes === 0) {
          //关闭加载中的这个图标
          wx.hideLoading();
        }
      },
    });
  });
};
